package com.devshephard.jucks.lock.readWriteLock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class readWriteLockTest {

    public static void main(String[] args) {

        MyCache  myCache = new MyCache();

        for (int i = 0; i < 10; i++) {
            final Integer temp = i;
            new Thread(()->{
                myCache.put(String.valueOf(temp),temp);
            },String.valueOf(i)).start();
        }

        for (int i = 0; i < 10; i++) {
            final Integer temp = i;
            new Thread(()->{
                myCache.get(String.valueOf(temp));
            },String.valueOf(i)).start();
        }

    }


}

class MyCache{

    private volatile Map<String,Object> cacheMap = new HashMap<>();

    //new一个读写锁对象（读写锁是对Lock所更细粒度的区分）
    private ReadWriteLock rdLock = new ReentrantReadWriteLock();

    public void put(String keyName,Integer value){

        //写锁进行加锁
        rdLock.writeLock().lock();

        try {
            System.out.println("存入:" + keyName + "值:" + String.valueOf(value));
            cacheMap.put(keyName,value);
            System.out.println("存入:" + keyName + "值:" + String.valueOf(value) + "完毕");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //写锁进行解锁
            rdLock.writeLock().unlock();
        }


    }

    public void get(String keyName){

        //读锁进行加锁
        rdLock.readLock().lock();

        try {
            System.out.println("读取:" + keyName + "值:" + cacheMap.get(keyName));
            Object o = cacheMap.get(keyName);
            System.out.println("读取:" + keyName + "值:" + cacheMap.get(keyName) + "完毕");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //读锁进行解锁
            rdLock.readLock().unlock();
        }


    }

}
